import React, { useState, useEffect } from 'react';

import { SendOutlined, DatabaseOutlined } from '@ant-design/icons';

import type { DeviceItemDetail, SysUploadDataOldType } from '@/api/deviceManagerApi';
import { deviceManagerDataSendApi, deviceManagerDataPushApi } from '@/api/deviceManagerApi';
import { DataTypeList, getEnumLabel } from '@/constants/common';
import clsx from 'clsx';

/**
 * 实时监控组件属性
 */
interface RealTimeMonitoringProps {
  /** 设备详情 */
  deviceDetail: DeviceItemDetail;
  /** 上报数据 */
  reportData: SysUploadDataOldType | null;
  /** 上报数据加载状态 */
  reportLoading: boolean;
  type: 'row' | 'col';
  /** 切换到属性记录回调 */
  onSwitchToPropertyRecords: (attributeName?: string) => void;
  /** 切换到服务记录回调 */
  onSwitchToServiceRecords: () => void;
}

/**
 * 属性数据接口
 */
interface PropertyData {
  /** 标识符 */
  identifier: string;
  /** 属性名称 */
  name: string;
  /** 属性值 */
  value: string;
  dataType: string;
  unit?: string;
}

interface ServiceData {
  identifier: string;
  name: string;
  inputData: Array<{
    identifier: string;
    name: string;
    dataType: string;
    value: string;
  }>;
}

/**
 * 实时监控组件
 */
const RealTimeMonitoring: React.FC<RealTimeMonitoringProps> = ({
  deviceDetail,
  reportData: _reportData,
  reportLoading: _reportLoading,
  onSwitchToPropertyRecords,
  onSwitchToServiceRecords,
  type,
}) => {
  const [loading, setLoading] = useState(false);
  const [propertyData, setPropertyData] = useState<PropertyData[]>([]);
  const [serviceData, setServiceData] = useState<ServiceData[]>([]);
  const [serviceInputs, setServiceInputs] = useState<Record<string, Record<string, string>>>({});

  // 解析设备元数据
  const parseDeviceMetadata = () => {
    if (!deviceDetail?.metaDataJson) return;

    try {
      const metaData =
        typeof deviceDetail.metaDataJson === 'string'
          ? JSON.parse(deviceDetail.metaDataJson)
          : deviceDetail.metaDataJson;

      // 解析属性数据
      if (metaData.properties && Array.isArray(metaData.properties)) {
        const properties: PropertyData[] = metaData.properties.map((prop: any) => ({
          identifier: prop.identifier,
          name: prop.name,
          value: '',
          dataType: prop.dataType?.type || 'string',
          unit: prop.dataType?.specs?.unit || '',
        }));
        setPropertyData(properties);
      }

      // 解析服务数据
      if (metaData.services && Array.isArray(metaData.services)) {
        const services: ServiceData[] = metaData.services.map((service: any) => ({
          identifier: service.identifier,
          name: service.name,
          inputData: service.inputData || [],
        }));
        setServiceData(services);

        // 初始化服务输入值
        const initialServiceInputs: Record<string, Record<string, string>> = {};
        services.forEach(service => {
          initialServiceInputs[service.identifier] = {};
          service.inputData.forEach((input: any) => {
            initialServiceInputs[service.identifier][input.identifier] = '';
          });
        });
        setServiceInputs(initialServiceInputs);
      }
    } catch (error) {
      console.error('解析设备元数据失败:', error);
    }
  };

  // 采集属性数据
  const handleCollectProperty = async (propertyIdentifier?: string) => {
    try {
      setLoading(true);

      const params: any = {
        productCode: deviceDetail.productCode,
        deviceCode: deviceDetail.code,
      };

      // 如果指定了属性标识符，只采集该属性
      if (propertyIdentifier) {
        params.paramKey = propertyIdentifier;
      }

      const res = await deviceManagerDataPushApi(params);
      if (res.success) {
        window.$message.success('数据采集成功');
        // 切换到属性记录页面
        onSwitchToPropertyRecords(propertyIdentifier);
      } else {
        window.$message.error(res.message || '数据采集失败');
      }
    } catch (error) {
      console.error('采集数据失败:', error);
      window.$message.error('采集数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 采集全部属性数据
  const handleCollectAllProperties = async () => {
    try {
      setLoading(true);

      const params = {
        productCode: deviceDetail.productCode,
        deviceCode: deviceDetail.code,
      };

      const res = await deviceManagerDataPushApi(params);
      if (res.success) {
        window.$message.success('全部数据采集成功');
        // 切换到属性记录页面
        onSwitchToPropertyRecords();
      } else {
        window.$message.error(res.message || '数据采集失败');
      }
    } catch (error) {
      console.error('采集数据失败:', error);
      window.$message.error('采集数据失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 下发服务数据
  const handleSendService = async (serviceIdentifier: string, sendAll: boolean = false) => {
    try {
      setLoading(true);

      const service = serviceData.find(s => s.identifier === serviceIdentifier);
      if (!service) {
        window.$message.error('服务不存在');
        return;
      }

      const inputParam: Record<string, string> = {};

      if (sendAll) {
        // 下发全部参数
        service.inputData.forEach(input => {
          const value = serviceInputs[serviceIdentifier]?.[input.identifier];
          if (value) {
            inputParam[input.identifier] = value;
          }
        });
      } else {
        // 只下发有值的参数
        service.inputData.forEach(input => {
          const value = serviceInputs[serviceIdentifier]?.[input.identifier];
          if (value) {
            inputParam[input.identifier] = value;
          }
        });
      }

      if (Object.keys(inputParam).length === 0) {
        window.$message.warning('请至少输入一个参数值');
        return;
      }

      const params = {
        identifier: serviceIdentifier,
        productCode: deviceDetail.productCode,
        deviceCode: deviceDetail.code,
        executionModel: 1,
        serviceName: service.name,
        inputParam,
      };

      const res = await deviceManagerDataSendApi(params);
      if (res.success) {
        window.$message.success('服务下发成功');
        // 切换到服务记录页面
        onSwitchToServiceRecords();
      } else {
        window.$message.error(res.message || '服务下发失败');
      }
    } catch (error) {
      console.error('下发服务失败:', error);
      window.$message.error('下发服务失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    parseDeviceMetadata();
  }, [deviceDetail.metaDataJson]);

  const spanInfo = useMemo(() => {
    if (type == 'col') {
      return 24;
    }
    return 12;
  }, [type]);
  const isCol = useMemo(() => {
    if (type == 'col') {
      return true;
    }
    return false;
  }, [type]);
  return (
    <div className={isCol ? 'whitespace-nowrap' : 'whitespace-nowra p-4'}>
      <ARow gutter={16} className={isCol ? 'mb-4' : ''}>
        {/* 左侧：采集数据 */}
        <ACol span={spanInfo}>
          <ACard
            title={
              <div className="flex items-center gap-2">
                <DatabaseOutlined style={{ color: '#0065f2' }} />
                <span className="text-gray-800 font-semibold">采集数据</span>
              </div>
            }
            extra={
              <ASpace>
                <AButton
                  type="primary"
                  size="small"
                  icon={<DatabaseOutlined />}
                  onClick={handleCollectAllProperties}
                  loading={loading}
                  style={{
                    backgroundColor: '#0065f2',
                    borderColor: '#0065f2',
                    boxShadow: 'none',
                  }}
                  className="hover:opacity-90"
                >
                  采集全部
                </AButton>
              </ASpace>
            }
            className="shadow-sm"
            styles={{ body: { padding: '16px', backgroundColor: '#fafafa' } }}
          >
            <div style={{ maxHeight: 400, overflowY: 'auto' }} className="pr-2">
              {propertyData.map(property => (
                <div
                  key={property.identifier}
                  className={clsx(
                    'mb-3  bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow',
                    {
                      'p-4': !isCol,
                      'p-2': isCol,
                    }
                  )}
                >
                  <div
                    className={clsx('mb-1', {
                      'flex items-center justify-between': !isCol,
                      'flex-col': isCol,
                    })}
                  >
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-800">{property.name}</span>
                      <ATag
                        style={{
                          backgroundColor: '#e6f4ff',
                          color: '#0065f2',
                          border: '1px solid #91caff',
                        }}
                        className="text-xs"
                      >
                        {getEnumLabel(DataTypeList, property.dataType, property.dataType)}
                      </ATag>
                    </div>
                    <div className="flex items-center gap-4">
                      <span
                        className="cursor-pointer text-sm"
                        style={{ color: '#0958d9' }}
                        onClick={() => onSwitchToPropertyRecords(property.identifier)}
                      >
                        历史数据
                      </span>
                      <span
                        className="cursor-pointer text-sm"
                        style={{ color: '#0958d9' }}
                        onClick={() => handleCollectProperty(property.identifier)}
                      >
                        采集
                      </span>
                    </div>
                  </div>
                  <div className="text-xs text-gray-500">标识符: {property.identifier}</div>
                </div>
              ))}

              {propertyData.length === 0 && (
                <div className="text-center text-gray-500 py-8">暂无属性数据</div>
              )}
            </div>
          </ACard>
        </ACol>

        {/* 右侧：下发数据 */}
        <ACol span={spanInfo}>
          <ACard
            title={
              <div className="flex items-center gap-2">
                <SendOutlined style={{ color: '#fa8c16' }} />
                <span className="text-gray-800 font-semibold">下发数据</span>
              </div>
            }
            extra={
              <ASpace>
                <AButton
                  type="primary"
                  size="small"
                  icon={<SendOutlined />}
                  onClick={() => {
                    // 下发全部服务的逻辑
                    serviceData.forEach(service => {
                      handleSendService(service.identifier, true);
                    });
                  }}
                  loading={loading}
                  style={{
                    backgroundColor: '#fa8c16',
                    borderColor: '#fa8c16',
                    boxShadow: 'none',
                  }}
                  className="hover:opacity-90"
                >
                  下发全部
                </AButton>
              </ASpace>
            }
            className="shadow-sm"
            styles={{ body: { padding: '16px', backgroundColor: '#fafafa' } }}
          >
            <div style={{ maxHeight: 400, overflowY: 'auto' }} className="pr-2">
              {serviceData.map(service => (
                <div
                  key={service.identifier}
                  className={clsx(
                    'mb-3  bg-white border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow',
                    {
                      'p-4': !isCol,
                      'p-2': isCol,
                    }
                  )}
                >
                  <div
                    className={clsx('mb-1', {
                      'flex items-center justify-between': !isCol,
                      'flex-col': isCol,
                    })}
                  >
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-gray-800">{service.name}</span>
                      <ATag
                        style={{
                          backgroundColor: '#fff7e6',
                          color: '#fa8c16',
                          border: '1px solid #ffd591',
                        }}
                        className="text-xs"
                      >
                        服务
                      </ATag>
                    </div>
                    <div className="flex items-center gap-4">
                      <span
                        className="cursor-pointer text-sm font-medium transition-colors"
                        style={{ color: '#1677ff' }}
                        onClick={onSwitchToServiceRecords}
                      >
                        历史服务
                      </span>
                      <span
                        className="cursor-pointer text-sm font-medium transition-colors"
                        style={{ color: '#fa8c16' }}
                        onClick={() => handleSendService(service.identifier, false)}
                      >
                        下发
                      </span>
                    </div>
                  </div>
                  <div className="text-xs text-gray-500 mb-3">标识符: {service.identifier}</div>

                  {/* 服务输入参数 */}
                  {service.inputData.map(input => (
                    <div key={input.identifier} className="mb-3">
                      <div className="text-sm text-gray-600 mb-1 font-medium">{input.name}</div>
                      <AInput
                        placeholder={`请输入${input.name}`}
                        value={serviceInputs[service.identifier]?.[input.identifier] || ''}
                        onChange={e => {
                          setServiceInputs(prev => ({
                            ...prev,
                            [service.identifier]: {
                              ...prev[service.identifier],
                              [input.identifier]: e.target.value,
                            },
                          }));
                        }}
                        style={{
                          borderColor: '#d9d9d9',
                        }}
                        onFocus={e => {
                          e.target.style.borderColor = '#0958d9';
                          e.target.style.boxShadow = '0 0 0 2px rgba(250, 140, 22, 0.2)';
                        }}
                        onBlur={e => {
                          e.target.style.borderColor = '#d9d9d9';
                          e.target.style.boxShadow = 'none';
                        }}
                      />
                    </div>
                  ))}
                </div>
              ))}

              {serviceData.length === 0 && (
                <div className="text-center text-gray-500 py-8">暂无服务数据</div>
              )}
            </div>
          </ACard>
        </ACol>
      </ARow>
    </div>
  );
};

export default RealTimeMonitoring;
